/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package common.xmlObjects;

import common.Objects.Category;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *<component>
 *	<id>1</id>
 *	<name>test1</name>
 *	<description>this is the test 1 component</description>
 *	<stock>0</stock>
 *	<price>10</price>
 *	<category>0</category>
 *</component>
 * @author Richard Irons
 */
public class CategoryXML extends XMLNode {
    public static final String ID = "id";
    public static final String NAME = "name";

    private XMLNode id;
    private XMLNode name;

    public CategoryXML() {
        this(null,null);
    }
    public CategoryXML(Category category) {
        this(
            String.valueOf(category.getId()),
            category.getName());
    }
    public CategoryXML (
            String id,
            String name) {

        super(BaseConnectionXML.CATEGORY,null);
        initChildren();

        setIdData(id);
        setNameData(name);
        reAttachChildren();
    }
    public CategoryXML (String xml) {
        this(BaseConnectionXML
            .XMLStrTODOMDoc(xml)
            .getElementsByTagName(
                BaseConnectionXML.CATEGORY)
                .item(0));
    }
    public CategoryXML (Node node) {
        this ();
        NodeList nodeList = node.getChildNodes();

        for (int j = 0; j < nodeList.getLength(); j++) {
            Element element = (Element) nodeList.item(j);
            String elementName = element.getTagName();
            String elementValue = element.getTextContent();
            if (elementName.equals(ComponentXML.ID)) {
                this.setIdData(elementValue);
            }
            else if (elementName.equals(ProductXML.NAME)) {
                this.setNameData(elementValue);
            }
        }
    }
    private void initChildren(){
        id = new XMLChildNode(ID,null);
        name = new XMLChildNode(NAME,null);
    }
    public void reAttachChildren() {
        this.removeAllChildNodes();
        addChildNode(id);
        addChildNode(name);
    }

    public Category getObject() {
        Category category = new Category();
        category.setId(Integer.parseInt(getIdData()));
        category.setName(getNameData());
        return category;
    }
    public String getIdData() {
        return id.getNodeData();
    }

    public void setIdData(String id) {
        if (id == null || id.isEmpty()) {
            id = "-1";
        }
        this.id.setNodeData(id);
        reAttachChildren();
    }

    public String getNameData() {
        return name.getNodeData();
    }

    public void setNameData(String name) {
        if (name == null || name.isEmpty()) {
            name = "";
        }
        this.name.setNodeData(name);
        reAttachChildren();
    }
}